<template>
	<!-- 海报 -->
	<view>
		<view>
			<canvas canvas-id="mini_poster" :style="{ width: canvasW + 'px', height: canvasH + 'px' }"></canvas>
		</view>
		<view style="height: 106rpx;"></view>
		<view class="footer">
			<view style="height: 106rpx; align-items: center; background-color: #FFF;">
				<button class="btn" @tap="checkPermissions">保存海报后分享</button>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		genWxMpQrCode
	} from "@/api/orderSalesman.js";
	export default {
		data() {
			return {
				canvasW: 0,
				canvasH: 0,
				cardPosterUrl:"https://oneredhealth.oss-cn-hangzhou.aliyuncs.com/2023/10/19/c1e7ec52ab1e46a8a032cbb203d49c49.jpg",//背景
				avatar: "https://oneredhealth.oss-cn-hangzhou.aliyuncs.com/2022/09/27/edb3c5f8680e439ea4e94d9cc762cfe4.png",//二维码
				finished: false,
			}
		},
		onLoad(op) {
			this.canvasW = uni.getSystemInfoSync().windowWidth
			this.canvasH = this.calculateCanvasHeight()
			this.QRcodeFun()
		},
		methods: {
			async QRcodeFun() {
				const res = await genWxMpQrCode({scene: 3});
				this.avatar= res.data.qrCodeUrl || this.avatar
				setTimeout(()=>{
					this.toDrawCanvas()	
				},500)
			},
			
			// 检查是否有权限
			checkPermissions () {
			  let that = this
			  // 获取用户是否开启 授权保存图片到相册。
			  uni.getSetting({
				success (res) {
					
				  // 如果没有授权
				  if (!res.authSetting['scope.writePhotosAlbum']) {
					// 则拉起授权窗口
					uni.authorize({
					  scope: 'scope.writePhotosAlbum',
					  success () {
						//点击允许后--就一直会进入成功授权的回调 就可以使用获取的方法了
						that.saveImg()
					
					  },
					  fail (error) {
						//点击了拒绝授权后--就一直会进入失败回调函数--此时就可以在这里重新拉起授权窗口
						uni.showModal({
						  title: '提示',
						  content: '若点击不授权，将无法保存图片',
						  cancelText: '不授权',
						  cancelColor: '#999',
						  confirmText: '授权',
						  confirmColor: '#f94218',
						  success (res) {
							if (res.confirm) {
							  // 选择弹框内授权
							  uni.openSetting({
								success (res) {
								}
							  })
							} else if (res.cancel) {
							  // 选择弹框内 不授权
							  console.log('用户点击不授权')
							}
						  }
						})
					  }
					})
				  } else {
					// 有权限--直接保存
					console.log('有权限  直接调用相应方法')
					that.toSaveImage()
					
				  }
				},
				fail: (error) => {
				  console.log('调用微信的查取权限接口失败，并不知道有无权限!只有success调用成功才只知道有无权限', error)
				  uni.showToast({
					title: error.errMsg,
					icon: 'none',
					duration: 1500,
				  })
				}
			  })
			},
			toSaveImage() {
				if (!this.finished) {
					uni.showToast({
						title: '正在生成图片，稍后再试',
						icon: 'none'
					})
					return
				}
				const that = this
				uni.canvasToTempFilePath({
					canvasId: 'mini_poster',
					success: (res) => {
						uni.saveImageToPhotosAlbum({
							filePath: res.tempFilePath,
							success: () => {
								uni.showToast({
									title: '保存成功'
								})
							},
							fail() {
								uni.showToast({
									icon: 'none',
									title: '保存名片码失败'
								})
							}
						})
					},
					fail() {
						uni.showToast({
							icon: 'none',
							title: '保存名片码失败'
						})
					}
				})
			},
			async toDrawCanvas() {
				const padding = uni.upx2px(28)
				const cardHeight = uni.upx2px(624)
				const hv = uni.upx2px(1000)
				const qwHx = uni.upx2px(240)//二维码得位置
				const qwHy = uni.upx2px(540)
				const cw = this.canvasW - 2 * padding

				let ctx = uni.createCanvasContext('mini_poster', this)

				ctx.setFillStyle('#fff')
				ctx.fillRect(0, 0, this.canvasW, this.canvasH)
				
				const r = uni.upx2px(12)
				const hi = await this.downloadImage(this.cardPosterUrl)
				if (hi.tempFilePath) {
					const x = padding 
					const y = padding
					this.drawRoundRectAvatar(ctx, x, y, cw, hv, r, hi.tempFilePath)
				}
				
				// 二维码
				const av = uni.upx2px(700)
				const hi1 = await this.downloadImage(this.avatar)
				if (hi1.tempFilePath) {
					const x = qwHx
					const r = uni.upx2px(20)
					const av = uni.upx2px(300)
					const y = qwHy
					this.drawRoundRectAvatar(ctx, x, y , av, av, r, hi1.tempFilePath)
				}
				
				ctx.draw()
				this.finished = true
			},
			//海报总高度
			calculateCanvasHeight() {
				const padding = uni.upx2px(34)
				const cardH = uni.upx2px(380)
				const hv = uni.upx2px(540)
				const h = padding * 4 + cardH + hv
				return h 
			},
			drawRoundRect(ctx, x, y, w, h, r, lineWidth) {
				ctx.save()
				this._drawRoundRect(ctx, x, y, w, h, r)
				ctx.clip()
				ctx.restore()
			},
			//图片的圆角
			_drawRoundRectPic(ctx, x, y, w, h, r ) {
				ctx.beginPath()
				// 左上角
				ctx.arc(x + r, y + r, r, Math.PI, Math.PI * 1.5)
				// 右上角
				ctx.arc(x + w - r, y + r, r, Math.PI * 1.5, Math.PI * 2)
				// 右下角
				ctx.arc(x + w - r, y + h - r, r, 0, Math.PI * 0.5)
				// 左下角
				ctx.arc(x + r, y + h - r, r, Math.PI * 0.5, Math.PI)
				ctx.closePath()
				ctx.fillStyle = '#FFFFFF';
				ctx.fill()
			},
			drawRoundRectPic(ctx, x, y, w, h, r, lineWidth) {
				ctx.save()
				this._drawRoundRect(ctx, x, y, w, h, r)
				ctx.clip()
				ctx.restore()
			},
			drawRoundRectAvatar(ctx, x, y, w, h, r, imgPath) {
				ctx.save()
				this._drawRoundRectPic(ctx, x, y, w, h, r,)
				ctx.clip()
				ctx.drawImage(imgPath, x, y, w, h)
				ctx.restore()
			},
			drawTextInLines(ctx, t, x, y, w, lineHeight) {
				const chr = t.split("")
				let temp = ''
				let row = []
				for (let i = 0; i < chr.length; i++) {
					if (ctx.measureText(temp).width < w) {
						//
					} else {
						row.push(temp)
						temp = ''
					}
					temp += chr[i]
				}
				row.push(temp)
				for (const i in row) {
					ctx.fillText(row[i], x, (y + (i * 1 + 1) * lineHeight))
				}
				return row.length
			},
			drawTextInOneLine(ctx, t, x, y, w) {
				const chr = t.split('')
				let temp = ''
				let row = []
				for (let i = 0; i < chr.length; i++) {
					if (ctx.measureText(temp).width < w) {
						temp += chr[i]
					} else {
						i--;//这里添加了a-- 是为了防止字符丢失，效果图中有对比        
						row.push(temp);
						temp = "";
					}
					// temp += chr[i]
				}
				row.push(temp)
				// //如果数组长度大于2 则截取前两个  
				if (row.length > 2) {
					var rowCut = row.slice(0, 2);
					var rowPart = rowCut[1];
					var test = "";
					var empty = [];
					for (var a = 0; a < rowPart.length; a++) {
						if (ctx.measureText(test).width <= w) {
							test += rowPart[a];
						} else {
							break;
						}
					}
					empty.push(test);
					var group = empty[0] + "..."//这里只显示两行，超出的用...表示      
					rowCut.splice(1, 1, group);
					row = rowCut;
				}
				for (var b = 0; b < row.length; b++) {
			       ctx.fillText(row[b], x, y + b * 15, w);
			    }
			},
			downloadImage(url) {
				return new Promise((resolve, reject) => {
					uni.downloadFile({
						url: url,
						success: (res) => {
							return resolve(res)
						},
						fail: (err) => {
							return reject(err)
						}
					})
				})
			}
		}
	}
</script>

<style>
	.btn{
			width: 694rpx;
			height: 74rpx;
			background: #588BF3;
			border-radius: 60rpx;
			text-align: center;
			line-height: 74rpx;
			color: #fff;
			font-size: 28rpx;
		}
	.footer {
			position: fixed;
			width: 100%;
			left: 0;
			bottom: 0;
			box-shadow: none;
		}
</style>
